package com.pignest.hotel.servlet;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.spring.ContextHolder;
import com.pignest.hotel.system.Config;

public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = -3064351925099027279L;
	
	public static String[] listImages(){
		String path = getBasePath();
		String images = path + File.separator + "images" + File.separator;
//		String thumbnails = path + File.separator + "thumbnails" + File.separator;
		File[] files = new File(images).listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {
				return file.isFile() && "jpg".equals(Utils.getExtention(file.getName()));
			}
		});
		String[] r = new String[files.length];
		for (int i = 0; i < files.length; i++) {
			r[i] = files[i].getName();
		}
		return r;
	}
	
	private static String getBasePath() {
		String path = Config.getSelfServiceImagePath();
		if (path == null)
			path = ContextHolder.getRealPath() + "/images/selfhelp/data";
		return path;
	}
	
	private void writeFile(HttpServletResponse resp, File f) throws IOException {
		if (f == null || !f.exists())
			f = new File(ContextHolder.getRealPath() + "images/7.png");
		resp.setContentType("image/*");
		resp.setContentLength((int)f.length());
		OutputStream out = resp.getOutputStream();
		InputStream in = new FileInputStream(f);
		byte[] buff = new byte[4096];
		int n;
		while ((n = in.read(buff)) != -1) {
			out.write(buff, 0, n);
		}
		in.close();
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String uri = req.getRequestURI();
		String[] es = StringUtils.split(uri, '/');
		if (es.length < 3)
			return;
		if (!"7h".equals(es[es.length - 3]))
			return;
		String type = es[es.length - 2];
		String path = getBasePath() + File.separator + type + File.separator + es[es.length - 1];
		writeFile(resp, new File(path));
	}
	
//	@Override
//	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		doGet(req, resp);
//	}
	
}
